/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.*;

/**
 * 一个{@link ExecutorService}, 它使用可能的几个线程池中的一个来执行
 * 每个提交的任务, 通常使用{@link Executors}工厂方法进行配置.
 *
 * <p>线程池解决了两个不同的问题:
 * 在执行大量异步任务时, 由于减少了每个任务的调用开销, 它们通常提供改进的性能;
 * 在执行一组任务时, 它们提供了一种绑定和管理资源(包括线程)的方法.
 * 每个{@code ThreadPoolExecutor}还维护着一些基本统计数据, 例如完成任务
 * 的数量.
 *
 * <p>为了在广泛的上下文中发挥作用, 该类提供了许多可调参数和可扩展性挂钩.
 * 然而, 程序员被敦促使用更方便的{@link Executors}工厂方法{@link
 * Executors#newCachedThreadPool} (无界线程池, 带有自动线程回收)、
 * {@link Executors#newFixedThreadPool}(固定大小的线程池)和{@link
 * Executors#newSingleThreadExecutor} (单后台线程), 它们为最常见的
 * 使用场景预先配置了设置. 否则, 在手动配置和调优该类时, 请使用以下指南:
 *
 * <dl>
 *
 * <dt>核心和最大池大小</dt>
 *
 * <dd>{@code ThreadPoolExecutor}将根据corePoolSize
 * (参见{@link #getCorePoolSize})和maximumPoolSize
 * (参见{@link #getMaximumPoolSize})设置的界限自动调整池大小
 * (参见{@link #getPoolSize}).
 *
 * 当在方法{@link #execute(Runnable)}中提交一个新任务, 并且运行的线程
 * 少于corePoolSize时, 即使其他工作线程空闲, 也会创建一个新线程来处理
 * 该请求. 如果运行的线程数大于corePoolSize但小于maximumPoolSize, 则
 * 只有队列已满时才会创建新线程. 通过将corePoolSize和maximumPoolSize
 * 设置为相同, 可以创建一个固定大小的线程池. 通过将maximumPoolSize设置为
 * 一个本质上不受限制的值, 例如{@code Integer.MAX_VALUE}, 你可以允许
 * 容纳任意数量的并发任务. 最典型的时, 核心和对打池大小仅在构造时设置, 但
 * 也可以使用{@link #setCorePoolSize}和{@link #setMaximumPoolSize}
 * 动态更改. </dd>
 *
 * <dt>按需创建</dt>
 *
 * <dd>默认情况下, 即使时核心线程最初也只有在新任务到达时才会创建和启动, 但是
 * 可以使用构造方法{@link #prestartCoreThread}或{@link
 * #prestartAllCoreThreads}动态覆盖这一点. 如果使用非空队列构造池, 可能
 * 需要预先启动线程. </dd>
 *
 * <dt>创建新线程</dt>
 *
 * <dd>使用{@link ThreadFactory}创建新线程. 如果没有另外指定, 则使用
 * {@link Executors#defaultThreadFactory}, 它将创建所有处于相同
 * {@link ThreadGroup}、具有相同{@code NORM_PRIORITY}优先级和非
 * 守护状态的线程. 通过提供不同的ThreadFactory, 你可以更改线程的名称、
 * 线程组、优先级、守护状态等. 如果{@code ThreadFactory}在请求时从
 * {@code newThread}返回null而未能创建线程, 则executor将继续, 但可能
 * 无法执行任何任务. 线程应该拥有"modifyThread" {@code RuntimePermission}.
 * 如果工作线程或使用池的其他线程不拥有此权限, 则服务可能会降级; 配置更改
 * 可能无法及时生效, 关闭池可能仍处于可以终止但尚未完成的状态.</dd>
 *
 * <dt>Keep-alive times</dt>
 *
 * <dd>如果池中当前有超过corePoolSize的线程, 多余的线程将被终止, 如果它们
 * 空闲时间超过keepAliveTime(参见{@link #getKeepAliveTime(TimeUnit)}).
 * 着提供了一种在池未被积极使用时减少资源消耗的方法. 如果池稍后变得更加活跃, 则将
 * 构造新的线程. 该参数也可以使用方法{@link #setKeepAliveTime(long,TimeUnit)}
 * 动态更改. 使用{@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS}值
 * 可以有效地禁止空闲线程在关闭之前终止. 默认情况下, 保持活动策略仅在线程数超过
 * corePoolSize时应用. 但是方法{@link #allowCoreThreadTimeOut(boolean)}
 * 也可以用于将此超时策略应用于核心线程, 只要keepAliveTime值不为零. </dd>
 *
 * <dt>Queuing</dt>
 *
 * <dd>任何{@link BlockingQueue}都可以用于转移和保留提交的任务. 这个队列的使用
 * 与池大小有关:
 *
 * <ul>
 *
 * <li>如果正在运行的线程少于corePoolSize, Executor总是倾向于添加一个新线程,
 * 而不是排队.</li>
 *
 * <li>如果corePoolSize或更多线程正在运行, Executor总是倾向于排队请求, 而不是
 * 添加一个新线程.</li>
 *
 * <li>如果请求不能排队, 则创建一个新线程, 除非它超过maximumPoolSize,
 * 在这种情况下, 任务将被拒绝.</li>
 *
 * </ul>
 *
 * 排队一般有三种策略:
 * <ol>
 *
 * <li> <em> Direct handoffs.</em> 对于工作队列来说, 一个很好的默认
 * 选择是{@link SynchronousQueue}, 它将任务交给线程, 而不保留它们.
 * 在这里, 如果没有线程可以立即运行, 那么对任务进行排队的尝试将失败, 因此
 * 将构造一个新线程. 在处理可能具有内部以来关系的请求时, 此策略可避免锁定.
 * 直接切换通常需要无限的maximumPoolSizes, 一避免拒绝新提交的任务.
 * 当命令大道的平均速度超过它们的处理速度时, 这反过来又承认了无限线程增长的
 * 可能性.  </li>
 *
 * <li><em> Unbounded queues.</em> 使用无边界队列(例如没有预定义容量
 * 的{@link LinkedBlockingQueue})将导致当所有corePoolSize线程当忙时,
 * 新任务在队列中等待. 因此, 不会创建超过corePoolSize的线程.
 * (因此max的值没有任何影响.) 当每个任务完全独立于其他任务时, 这可能是合适的,
 * 因此任务不会影响彼此的执行; 例如, 在web页面服务器中. 虽然这种类型的队列在
 * 平滑瞬时请求爆发方面很有用, 但是当命令继续以平均快于处理速度到达时, 它承认
 * 了无限制工作队列增长的可能性. </li>
 *
 * <li><em>Bounded queues.</em> 当使用有限的maximumPoolSizes时, 有界
 * 队列(例如{@link ArrayBlockingQueue})有助于防止资源耗尽, 但可能更难以调优
 * 和控制. 队列大小和最大池大小可以相互权衡; 使用大队列和小池可以最大限度地减少
 * CPU使用、操作系统资源和上下文切换开销, 但可能导致人为地降低吞吐量. 如果任务经常
 * 阻塞(例如, 如果它们时I/O绑定的), 系统可能能够为比你允许的更多的线程安排时间.
 * 使用小队列通常需要更大的池大小, 这会使CPU更忙, 但可能会遇到不可接受的速度开销,
 * 这也会降低吞吐量. </li>
 *
 * </ol>
 *
 * </dd>
 *
 * <dt>拒绝任务</dt>
 *
 * <dd>在方法{@link #execute(Runnable)}中提奖的新任务将在Executor
 * 关闭时被<em>拒绝</em>, 并且当Executor对最大线程和工作队列容量使用
 * 有限界限并且饱和时也会被拒绝. 无论哪种情况, {@code execute}方法
 * 都会调用其{@link RejectedExecutionHandler}的{@link
 * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
 * 方法. 提供了四个预先定义的处理程序策略:
 *
 * <ol>
 *
 * <li>在默认的{@link AbortPolicy}中, handler在拒绝时抛出
 * 运行时{@link RejectedExecutionException}. </li>
 *
 * <li>在{@link CallerRunsPolicy}中, 调用{@code execute}
 * 的线程本身运行任务. 这提供了一种简单的反馈控制机制, 可以降低新任务
 * 提交的速度. </li>
 *
 * <li>在{@link DiscardPolicy}中, 不能执行的任务被简单地丢弃. </li>
 *
 * <li>在{@link DiscardOldestPolicy}中, 如果executor未关闭,
 * 则丢弃工作队列头部的任务, 然后重试执行(可能再次失败, 从而导致重复
 * 执行). </li>
 *
 * </ol>
 *
 * 可以定义和使用其他类型的{@link RejectedExecutionHandler}类.
 * 这样做需要一些小心, 特别是当策略被设计为仅特定容量会排队策略下工作时. </dd>
 *
 * <dt>Hook methods</dt>
 *
 * <dd>这个类提供了{@code protected}可重写的
 * {@link #beforeExecute(Thread, Runnable)}和
 * {@link #afterExecute(Runnable, Throwable)}方法, 它们在执行
 * 每个任务之前和之后被调用. 这些可以用于操作执行环境; 例如, 重新初始化
 * ThreadLocals、收集统计信息或添加日志条目. 此外, 可以重写方法
 * {@link #terminated}, 以执行在Executor完全终止胡需要执行的任何
 * 特殊处理.
 *
 * <p>如果狗子或回调方法抛出异常, 内部工作线程可能会失败并突然终止.</dd>
 *
 * <dt>队列的维护</dt>
 *
 * <dd>方法{@link #getQueue()}允许访问工作队列以进行监视和调试. 强烈
 * 反对将此方法用于任何其他目的. 当大量排队的任务被取消时, 提供的两种方法
 * {@link #remove(Runnable)}和{@link #purge}可用于协助存储回收.</dd>
 *
 * <dt>Finalization</dt>
 *
 * <dd>程序中不再引用<em>并且</em>没有剩余线程的池将自动被{@code shutdown}.
 * 如果你想确保即使用户忘记调用{@link #shutdown}, 也能回收未引用的池, 那么你
 * 必须通过设置适当的保活时间、使用零核心线程的下限and/or设置
 * {@link #allowCoreThreadTimeOut(boolean)}来安排未使用的线程最终死亡.  </dd>
 *
 * </dl>
 *
 * <p><b>Extension example</b>. 这个类的大多数扩展重写一个活多个受保护
 * 的钩子方法. 例如, 下面时一个子类, 它添加了一个简单的pause/resume功能:
 *
 *  <pre> {@code
 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
 *   private boolean isPaused;
 *   private ReentrantLock pauseLock = new ReentrantLock();
 *   private Condition unpaused = pauseLock.newCondition();
 *
 *   public PausableThreadPoolExecutor(...) { super(...); }
 *
 *   protected void beforeExecute(Thread t, Runnable r) {
 *     super.beforeExecute(t, r);
 *     pauseLock.lock();
 *     try {
 *       while (isPaused) unpaused.await();
 *     } catch (InterruptedException ie) {
 *       t.interrupt();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void pause() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = true;
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void resume() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = false;
 *       unpaused.signalAll();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 * }}</pre>
 *
 * @since 1.5
 * @author Doug Lea
 */
public class ThreadPoolExecutor extends AbstractExecutorService {
    /**
     * main池控制状态ctl时一个原子整型, 包含两个概念字段
     * workerCount, 指示有效线程数runState, 指示是否正在运行、关闭等.
     *
     * 为了将他们打包成一个int, 我们将workerCount限制为(2^29)-1
     * (大约五亿)个线程, 而不是(2^31)-1 (20亿)个线程. 如果将来出现
     * 这个问题, 可以将变量更改为AtomicLong, 并调整下面的shift/mask
     * 常量. 但是在需要之前, 这段代码使用int会更快更简单一些.
     *
     * workerCount是允许启动而不允许停止的worker的数量. 该值可能与
     * 活动线程的实际数量暂时不同, 例如, 当ThreadFactory在被要求创建
     * 线程时失败, 以及退出的线程在终止之前仍在执行记账时. 用户可见的
     * 池大小报告为worker set的当前大小.
     *
     * runState提供了主要的生命周期监控, 接受值:
     *
     *   RUNNING:  接受新任务并处理排队任务
     *   SHUTDOWN: 不接受新任务, 而是处理已排队的任务
     *   STOP:     不接受新任务, 不要处理排队的任务, 不要中断正在进行的任务
     *   TIDYING:  所有任务都已终止, workerCount为零, 线程转换到TIDYING
     *             状态将运行terminated()钩子方法
     *   TERMINATED: terminated()已完成
     *
     * 为了运行有序比较, 这些值之间的数字顺序很重要. runState单调地随时间增加,
     * 但不需要达到这个状态. 过渡是:
     *
     * RUNNING -> SHUTDOWN
     *    在调用shutdown()时, 可能隐式地调用finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    调用shutdownNow()时
     * SHUTDOWN -> TIDYING
     *    当队列和池都为空时
     * STOP -> TIDYING
     *    当池空了
     * TIDYING -> TERMINATED
     *    当terminated()钩子方法完成时
     *
     * 在awaitTermination()中等待的线程将在状态达到TERMINATED时return.
     *
     * 检测从SHUTDOWN到TIDYING的转换并不像你想的那么简单, 因为SHUTDOWN
     * 状态期间, 队列可能在非空之后变为空, 反之亦然, 但是我们只能在看到队列
     * 为空之后, 看到workerCount为0(这有时需要重新检查 -- 见下文)时终止.
     */
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // runState is stored in the high-order bits
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

    // Packing and unpacking ctl
    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static int ctlOf(int rs, int wc) { return rs | wc; }

    /*
     * 不要拆包ctl的位字段访问器.
     * 这些取决于位布局和workerCount永远不会为负.
     */

    private static boolean runStateLessThan(int c, int s) {
        return c < s;
    }

    private static boolean runStateAtLeast(int c, int s) {
        return c >= s;
    }

    private static boolean isRunning(int c) {
        return c < SHUTDOWN;
    }

    /**
     * 试图CAS-increment ctl的workerCount字段.
     */
    private boolean compareAndIncrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect + 1);
    }

    /**
     * 尝试CAS-decrement ctl的workerCount字段.
     */
    private boolean compareAndDecrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect - 1);
    }

    /**
     * 减少ctl的workerCount字段. 这只在线程突然终止时调用
     * (参见processWorkerExit). 其他decrements在getTask中执行.
     */
    private void decrementWorkerCount() {
        do {} while (! compareAndDecrementWorkerCount(ctl.get()));
    }

    /**
     * 用于保存任务和将任务移交给worker线程的队列. 我们不要求
     * workQueue.poll()返回null一定意味着workQueue.isEmpty(),
     * 所以只依赖于isEmpty来查看队列是否为空(例如, 当觉得是否从SHUTDOWN
     * 转换到TIDYING时, 我们必须这样做). 这适用于特殊用途的队列, 如
     * DelayQueues, 其中poll()运行返回null, 即使它可能在延迟过期后返回非null.
     */
    private final BlockingQueue<Runnable> workQueue;

    /**
     * 锁定worker设置和相关记账的访问权限. 虽然我们可以使用某种concurrent set，
     * 但事实证明, 使用锁通常更可取. 其中一个原因是它序列化了interruptIdleWorkers,
     * 从而避免了不必要的中断风暴, 尤其是在关闭期间. 否则, 退出的线程将同时中断
     * 那些尚未中断的线程. 它还简化了largestPoolSize等的一些相关统计记账.
     * 我们还在shutdown和shutdown时保持mainLock. 为了确保worker设置稳定,
     * 同时分别检查中断和实际中断的权限.
     */
    private final ReentrantLock mainLock = new ReentrantLock();

    /**
     * 包含池中所有worker线程的集合. 只有在持有mainLock时才能访问.
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();

    /**
     * 支持awaitTermination的条件等待
     */
    private final Condition termination = mainLock.newCondition();

    /**
     * 跟踪已达到的最大池大小. 仅在mainLock下访问.
     */
    private int largestPoolSize;

    /**
     * 已完成任务的计数器. 尽在worker线程终止时更新.
     * 仅在mainLock下访问.
     */
    private long completedTaskCount;

    /*
     * 所有用户控制参数都生命为volatiles, 因此正在进行的操作基于最新的值,
     * 但不需要锁定, 因为没有内部不变量依赖于它们相对于其他操作同步更改.
     */

    /**
     * 新线程的工厂. 所有线程都是使用这个工厂创建的(通过addWorker方法).
     * 所有调用方法都必须为addWorker失败做好准备, 这可能反应了系统或
     * 用户限制线程数量的策略. 即使不将其视为错误, 创建线程失败也可能导致
     * 新任务被拒绝或现有任务滞留在队列中.
     *
     * 我们更进一步, 即使面对OutOfMemoryError等错误, 也会保留池不变量,
     * 这些错误可能是在尝试创建线程时抛出的. 由于需要再Thread.start中
     * 分配本机堆栈, 这样的错误非常常见, 并且用户希望执行清理池关闭来进行
     * 清理. 可能有足够的内存可供清理代码在不遇到另一个OutOfMemoryError
     * 的情况下完成.
     */
    private volatile ThreadFactory threadFactory;

    /**
     * 在执行中饱和或关闭时调用的handler.
     */
    private volatile RejectedExecutionHandler handler;

    /**
     * 等待工作的空闲线程的超时时间(以纳秒为单位). 当存在超过
     * corePoolSize或allowCoreThreadTimeOut时, 线程使用此超时.
     * 否则, 他们会永远等待新工作.
     */
    private volatile long keepAliveTime;

    /**
     * 如果为false(默认), 核心线程即使在空闲时也保持活动.
     * 如果为true, 核心线程使用keepAliveTime超时等待工作.
     */
    private volatile boolean allowCoreThreadTimeOut;

    /**
     * 核心池大小是指除非设置了allowCoreThreadTimeOut, 否则要保持活动
     * 状态(并且不允许超时等)的最小worker线程数, 在这种情况下, 最小值为零.
     */
    private volatile int corePoolSize;

    /**
     * 最大池大小. 请注意, 实际最大值在内部受容量限制.
     */
    private volatile int maximumPoolSize;

    /**
     * 默认的拒绝执行handler
     */
    private static final RejectedExecutionHandler defaultHandler =
        new AbortPolicy();

    /**
     * shutdown和shutdownNow的调用方需要权限. 我们还要求
     * (参见checkShutdownAccess)调用者有权实际中断worker集中的
     * 线程(由Thread.interrupt管理, 它依赖于ThreadGroup.checkAccess,
     * 而ThreadGroup.checkAccess又依赖于SecurityManager.checkAccess).
     * 只有当这些检查通过时, 才会尝试关闭.
     *
     * 所有对Thread.interrupt的实际调用(参见interruptIdleWorkers
     * 和interruptWorkers)都会忽略SecurityExceptions, 这意味着尝试
     * 的中断将以静默方式失败. 在关闭的情况下, 它们不应该失败, 除非SecurityManager
     * 具有不一致的策略, 有时允许访问线程, 有时不允许. 在这种情况下, 无法
     * 实际中断线程可能会禁用或延迟完全终止. interruptIdleWorkers的其他
     * 用途时咨询性的, 如果不能真正中断, 只会延迟对配置更改的响应, 因此不会
     * 异常处理.
     */
    private static final RuntimePermission shutdownPerm =
        new RuntimePermission("modifyThread");

    /* T执行finalizer时要使用的context, 或null. */
    private final AccessControlContext acc;

    /**
     * Class Worker主要维护运行任务的线程的中断控制状态, 以及它次要的记账.
     * 这个类适当地扩展了AbstractQueuedSynchronizer, 以简化获取和释放
     * 围绕每个任务执行的lock. 这可以防止中断, 这些中断旨在唤醒等待任务的
     * 工作线程, 而不是中断正在运行的任务. 我们实现了一个简单的不可重入互斥
     * 锁, 而不是使用ReentrantLock, 因为我们不希望工作任务在调用setCorePoolSize
     * 等池控制方法时能够重新获得锁. 此外, 为了在线程实际开始运行任务之前
     * 抑制中断, 我们将锁状态初始化为负值, 并在启动时(在runWorker中)清除它.
     */
    private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
        /**
         * 这个类永远不会被序列化, 但是我们提供了一个serialVersionUID
         * 来抑制javac警告.
         */
        private static final long serialVersionUID = 6138294804551838833L;

        /** 此worker线程正在运行的线程. 如果factory失败, 则为null. */
        final Thread thread;
        /** 要运行的初始任务. 可能为null. */
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;

        /**
         * 使用ThreadFactory中给定的第一个任务和线程创建.
         * @param firstTask 第一个任务(如果没有, 则为null)
         */
        Worker(Runnable firstTask) {
            setState(-1); // 禁止中断, 直到runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /** 将主运行循环委托给外部runWorker  */
        public void run() {
            runWorker(this);
        }

        // Lock methods
        //
        // 值0表示未锁定状态.
        // 值1表示锁定状态.

        protected boolean isHeldExclusively() {
            return getState() != 0;
        }

        protected boolean tryAcquire(int unused) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        protected boolean tryRelease(int unused) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        public void lock()        { acquire(1); }
        public boolean tryLock()  { return tryAcquire(1); }
        public void unlock()      { release(1); }
        public boolean isLocked() { return isHeldExclusively(); }

        void interruptIfStarted() {
            Thread t;
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
    }

    /*
     * 设置控制状态的方法
     */

    /**
     * 将runState转换到给定的目标, 或者如果至少以及时给定的目标
     * 则不使用它.
     *
     * @param targetState 所需的状态, SHUTDOWN或STOP
     *        (但不是TIDYING或TERMINATED -- 请使用tryTerminate)
     */
    private void advanceRunState(int targetState) {
        for (;;) {
            int c = ctl.get();
            if (runStateAtLeast(c, targetState) ||
                ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
                break;
        }
    }

    /**
     * 如果(SHUTDOWN且池和队列为空)或(STOP且池为空), 则转换为TERMINATED
     * 状态. 如果有资格终止, 但workerCount为非零, 则中断空闲的worker以确保
     * 关闭信号传播. 必须在在还行任何可能导致终止的操作(减少工作人员数量或关闭
     * 期间从队列中删除任务)之后调用此方法. 该方法是非private的, 以允许从
     * ScheduledThreadPoolExecutor进行访问.
     */
    final void tryTerminate() {
        for (;;) {
            int c = ctl.get();
            if (isRunning(c) ||
                runStateAtLeast(c, TIDYING) ||
                (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
                return;
            if (workerCountOf(c) != 0) { // 有资格终止
                interruptIdleWorkers(ONLY_ONE);
                return;
            }

            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
                    try {
                        terminated();
                    } finally {
                        ctl.set(ctlOf(TERMINATED, 0));
                        termination.signalAll();
                    }
                    return;
                }
            } finally {
                mainLock.unlock();
            }
            // 否则在失败的CAS上重试
        }
    }

    /*
     * 用于控制worker线程中断的方法.
     */

    /**
     * 如果有security manager, 请确保调用方具有关闭线程的权限
     * (参见shutdownPerm). 如果通过, 则另外确保运行调用方中断
     * 每个工作线程. 即使通过了第一次检查, 如果SecurityManager
     * 对某些线程进行了特殊处理, 这也可能不是真的.
     */
    private void checkShutdownAccess() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPermission(shutdownPerm);
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                for (Worker w : workers)
                    security.checkAccess(w.thread);
            } finally {
                mainLock.unlock();
            }
        }
    }

    /**
     * 中断所有线程, 即使处于活动状态. 忽略SecurityExceptions
     * (在这种情况下, 某些线程可能保持不中断).
     */
    private void interruptWorkers() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers)
                w.interruptIfStarted();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 中断可能正在等待任务的线程(如未锁定所示), 一遍检查终止或配置更改.
     * 忽略Se某些线程可能保持不中断).
     *
     * @param onlyOne 如果为true, 则最多打断一个worker. 仅当以其他方式
     * 启用终止但仍有其他worker时, 才从tryTerminate调用此操作. 在这种情况
     * 下, 在所有线程当前都在等待的情况下, 最多会中断一个等待的worker进程来
     * 传播关闭信号. 中断任意线程可以确保自关闭开始以来新到达的worker最终也会
     * 退出. 为了保证最终终止, 总是只中断一个空闲的worker就足够了, 但shutdown()
     * 会中断所有空闲的worker, 这样多余的worker就会迅速退出, 而不是等待一个
     * 掉队的任务完成.
     */
    private void interruptIdleWorkers(boolean onlyOne) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers) {
                Thread t = w.thread;
                if (!t.isInterrupted() && w.tryLock()) {
                    try {
                        t.interrupt();
                    } catch (SecurityException ignore) {
                    } finally {
                        w.unlock();
                    }
                }
                if (onlyOne)
                    break;
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * interruptIdleWorkers的常见形式, 以避免必须记住boolean参数的含义.
     */
    private void interruptIdleWorkers() {
        interruptIdleWorkers(false);
    }

    private static final boolean ONLY_ONE = true;

    /*
     * 其他实用程序, 其中大部分也导出到ScheduledThreadPoolExecutor
     */

    /**
     * 为给定的command调用拒绝策略.
     * 受保护的包可由ScheduledThreadPoolExecutor使用.
     */
    final void reject(Runnable command) {
        handler.rejectedExecution(command, this);
    }

    /**
     * 在调用shutdown时执行运行状态转换之后的任何进一步清理. 这里
     * 没有操作, 但由ScheduledThreadPoolExecutor用于取消延迟
     * 的任务.
     */
    void onShutdown() {
    }

    /**
     * ScheduledThreadPoolExecutor需要进行状态检查,
     * 以便在关闭期间启用正在运行的任务.
     *
     * @param shutdownOK true if should return true if SHUTDOWN
     */
    final boolean isRunningOrShutdown(boolean shutdownOK) {
        int rs = runStateOf(ctl.get());
        return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
    }

    /**
     * 将任务队列排入新列表, 通常使用drainTo. 但是, 如果队列是DelayQueue
     * 或poll或drainTo可能无法删除某些元素的任何其他类型的队列, 它会逐一
     * 删除这些元素.
     */
    private List<Runnable> drainQueue() {
        BlockingQueue<Runnable> q = workQueue;
        ArrayList<Runnable> taskList = new ArrayList<Runnable>();
        q.drainTo(taskList);
        if (!q.isEmpty()) {
            for (Runnable r : q.toArray(new Runnable[0])) {
                if (q.remove(r))
                    taskList.add(r);
            }
        }
        return taskList;
    }

    /*
     * 创建、运行和清理worker后的方法M
     */

    /**
     * 检查是否可以根据当前池状态和给定绑定(core或maximum)添加新的
     * 辅助进程. 如果是, 则会相应地调整worker计数, 如果可能, 则会
     * 创建并启动一个新的worker, 将firstTask作为其第一个任务运行.
     * 如果池已停止或有资格关闭, 此方法将返回false. 如果线程工厂在
     * 被请求时未能创建线程, 它也会返回false. 如果线程创建失败, 无论
     * 是由于线程工厂返回null, 还是由于异常(通常是thread.start()
     * 中的OutOfMemoryError), 我们都会干净地回滚.
     *
     * @param firstTask 新线程应该首先运行的任务(如果没有, 则为null).
     * 当线程少于corePoolSize时(在这种情况下, 我们总是启动一个线程),
     * 或者当队列已满时(在那种情况下, 必须绕过队列), 会创建一个初始的第一个
     * 任务(在方法execute()中)来绕过排队. 最初的空闲线程通常是通过
     * prestartCoreThread创建的, 或者用来替换其他垂死的worker线程.
     *
     * @param core 如果为true, 则使用corePoolSize作为绑定, 否则
     * 使用maximumPoolSize. (此处使用boolean指示符而不是值, 以确保
     * 在检查其他池状态后读取新值).
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // 仅在必要时检查队列是否为空.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // 否则, 由于workerCount更改, CAS失败; 重试内部循环
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // 持有锁时重新检查.
                    // 退出ThreadFactory故障或在获取锁之前关闭.
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // 预先检查t是否可启动
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

    /**
     * 回滚worker线程创建.
     * - 从workers中移除worker, 如果存在
     * - 减少worker人数
     * - 重新检查是否终止合同, 以防该worker的存在阻碍了终止合同
     */
    private void addWorkerFailed(Worker w) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (w != null)
                workers.remove(w);
            decrementWorkerCount();
            tryTerminate();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 为一个垂死的worker进行清理和记账. 仅从worker线程调用. 除非
     * 设置了completedAbruptly, 否则假设workerCount已经调整为退出.
     * 此方法从worker线程集中删除线程, 如果由于用户任务异常而退出, 或者
     * 运行的工作线程少于corePoolSize, 或者队列为非空但没有worker线程,
     * 则可能终止池或替换worker线程.
     *
     * @param w the worker
     * @param completedAbruptly 如果worker因用户异常而死亡
     */
    private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // 如果突然的, 则workerCount未被调整
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
        } finally {
            mainLock.unlock();
        }

        tryTerminate();

        int c = ctl.get();
        if (runStateLessThan(c, STOP)) {
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            addWorker(null, false);
        }
    }

    /**
     * 执行阻塞或定时等待任务, 取决于当前的配置设置, 或者返回null, 如果
     * 这个worker线程必须退出, 因为:
     * 1. 有超过maximumPoolSize的worker(由于调用setMaximumPoolSize).
     * 2. 池停止运行.
     * 3. 池已经shutdown, 队列为空.
     * 4. 该worker线程超时等待任务, 超时的worker线程在定时等待之前和之后都会
     *    终止(即{@code allowCoreThreadTimeOut || workerCount > corePoolSize}),
     *    如果队列非空, 则该worker线程不是池中的最后一个线程.
     *
     * @return 如果worker必须退出, 则返回null, 在这种情况下, workerCount将递减
     */
    private Runnable getTask() {
        boolean timedOut = false; // 上次poll()超时了吗?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // 仅在必要时检查队列是否为空.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            // worker会被淘汰吗?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

    /**
     * main worker运行循环. 重复地从队列中获取任务并执行它们, 同时
     * 处理一些问题:
     *
     * 1. 我们可以池欧诺个初始任务开始, 在这种情况下, 我们不需要获得第一个
     * 任务. 否则, 只要pool正在运行, 我们就会从getTask获取任务. 如果它
     * 返回null, 则由于poll状态或配置参数更改, worker退出. 其他退出是
     * 由外部代码中的异常抛出引起的, 在这种情况下completedAbruptly
     * 保持不变, 这通常导致processWorkerExit替换此线程.
     *
     * 2. 在运行任何任务之前, 获取锁以防止任务执行时其他pool中断, 然后
     * 我们确保除非pool停止, 否则该线程不会设置中断.
     *
     * 3. 每次任务运行之前都会调用beforeExecute, 这可能会引发异常,
     * 在这种情况下, 我们会导致线程在不处理任务的情况下死亡
     * (用completedAbruptly true打断循环).
     *
     * 4. 假设beforeExecute正常完成, 我们运行该任务, 收集其抛出的任何
     * 异常发送到afterExecute. 我们分别处理RuntimeException、Error
     * (规范保证会捕获这两种情况)和任意Throwables. 因为我们不能在
     * Runnable.run中重新抛出Throwables, 所以我们在退出时(到线程的
     * UncaughtExceptionHandler)将他们包装在Errors中. 任何抛出的
     * 异常都会保守地导致线程死亡.
     *
     * 5. 在task.run完成后, 调用afterExecute, 这也可能抛出异常,
     * 这也会导致线程失望. 根据JLS第14.20节, 即使task.run抛出, 这个
     * 异常也会生效.
     *
     * 异常机制的最终效果是, afterExecute和线程的UncaughtExceptionHandler
     * 拥有关于用户代码遇到的任何问题的尽可能准确的信息.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // 如果pool正在停止, 确保线程被中断;
                // 如果不是, 确保线程没有中断.
                // 这需要再第二种情况下重新检查, 以在清除中断时处理
                // shutdownNow竞争
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

    // public构造器和方法

    /**
     * 使用给定的初始参数、默认线程工厂和拒绝策略handler创建一个新的
     * {@code ThreadPoolExecutor}. 使用{@link Executors}工厂
     * 方法可能比使用这个通用构造函数更方便.
     *
     * @param corePoolSize 要保留在pool中的线程数, 即使他们是空闲的,
     *        除非设置了{@code allowCoreThreadTimeOut}
     * @param maximumPoolSize pool中运行的最大线程数
     * @param keepAliveTime 当线程数大于core时, 这是多余空闲线程在终止前
     *        等待新任务的最大时间.
     * @param unit {@code keepAliveTime}参数的时间单位
     * @param workQueue 在任务执行之前用于保存任务的队列. 这个队列将只容纳
     *        {@code execute}方法提交的{@code Runnable}任务.
     * @throws IllegalArgumentException 如果下列条件之一成立:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException 如果{@code workQueue}为null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

    /**
     * 使用给定的初始参数和默认拒绝策略handler创建新的
     * {@code ThreadPoolExecutor}.
     *
     * @param corePoolSize 要保留在池中的线程数, 即使它们是空闲的, 除非设置了
     * {@code allowCoreThreadTimeOut}
     * @param maximumPoolSize pool中允许的最大线程数
     * @param keepAliveTime 当线程数大于core时, 这是多余空闲线程在终止
     *        前等待新任务的最大时间.
     * @param unit {@code keepAliveTime}参数的时间单位
     * @param workQueue 在任务执行之前用于保存任务的队列. 这个队列将只容纳
     *        {@code execute}方法提交的{@code Runnable}任务.
     * @param threadFactory executor创建新线程是要使用的工厂
     * @throws IllegalArgumentException 如果以下情况之一成立:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException 如果{@code workQueue}
     *         或{@code threadFactory}为null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

    /**
     * 使用给定的初始参数和默认线程工厂创建一个新的{@code ThreadPoolExecutor}.
     *
     * @param corePoolSize 要保留在池中的线程数, 即使它们是空闲的, 除非设置了
     * {@code allowCoreThreadTimeOut}
     * @param maximumPoolSize pool中允许的最大线程数
     * @param keepAliveTime 当线程数大于core时, 这是多余空闲线程在终止
     *        前等待新任务的最大时间.
     * @param unit {@code keepAliveTime}参数的时间单位
     * @param workQueue 在任务执行之前用于保存任务的队列. 这个队列将只容纳
     *        {@code execute}方法提交的{@code Runnable}任务.
     * @param handler 当由于达到线程边界和队列容量而阻止执行时要使用的handler
     * @throws IllegalArgumentException 如果以下情况之一成立:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException 如果{@code workQueue}
     *         或{@code handler}为null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }

    /**
     * 使用给定的初始化参数创建一个新的{@code ThreadPoolExecutor}.
     *
     * @param corePoolSize 要保留在池中的线程数, 即使它们是空闲的, 除非设置了
     * {@code allowCoreThreadTimeOut}
     * @param maximumPoolSize pool中允许的最大线程数
     * @param keepAliveTime 当线程数大于core时, 这是多余空闲线程在终止
     *        前等待新任务的最大时间.
     * @param unit {@code keepAliveTime}参数的时间单位
     * @param workQueue 在任务执行之前用于保存任务的队列. 这个队列将只容纳
     *        {@code execute}方法提交的{@code Runnable}任务.
     * @param threadFactory executor创建新线程是要使用的工厂
     * @param handler 当由于达到线程边界和队列容量而阻止执行时要使用的handler
     * @throws IllegalArgumentException 如果以下情况之一成立:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException 如果{@code workQueue}
     *         或{@code threadFactory}或{@code handler}为null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

    /**
     * 在将来某个时候执行给定的任务.
     * 该任务可以在新线程中执行, 也可以在现有线程池中执行.
     *
     * 如果由于此executor已关闭或已达到其容量, 任务无法提交执行,
     * 则由当前{@code RejectedExecutionHandler}处理.
     *
     * @param command 要执行的任务
     * @throws RejectedExecutionException 如果任务不能被接收执行,
     *         则由{@code RejectedExecutionHandler}自行决定
     * @throws NullPointerException 如果{@code command}为null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * 按照3个步骤进行:
         *
         * 1. 如果运行的线程少于corePoolSize, 请尝试以给定的command作为
         * 第一个任务来启动一个新线程. 对addWorker的调用原子性地检查runState
         * 和workerCount, 从而通过返回false来防止错误警报, 这些从错误警报
         * 会在不应该添加线程的情况下添加线程.
         *
         * 2. 如果一个任务可以成功排队, 那么我们仍然需要仔细检查我们是否应该
         * 添加一个线程(因为现有线程自上次检查依赖已经失效), 或者pool自进入
         * 该方法依赖已经关闭. 因此, 我们重新检查状态, 如果有必要, 如果停止,
         * 则回滚排队, 如果没有, 则启动一个新线程.
         *
         * 3. 如果我们不能对任务进行排队, 那么我们将尝试添加一个新线程.
         * 如果它失败了, 我们知道我们已经关闭或饱和了, 所以拒绝执行任务.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

    /**
     * 启动有序shutdown, 在此shutdown中执行以前提交的任务, 但不接受任何新任务.
     * 如果调用已经关闭, 则不会产生额外效果.
     *
     * <p>此方法不等待以前提交的任务完成执行. 用
     * {@link #awaitTermination awaitTermination}来做.
     *
     * @throws SecurityException {@inheritDoc}
     */
    public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
            interruptIdleWorkers();
            onShutdown(); // ScheduledThreadPoolExecutor的钩子
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }

    /**
     * 尝试停止所有正在执行的任务, 停止处理等待的任务, 并返回等待执行的任务列表.
     * 从该方法返回后, 这些任务将从任务队列中排出(删除).
     *
     * <p>此方法不等待主动执行的任务终止. 用
     * {@link #awaitTermination awaitTermination}来做.
     *
     * <p>除了尽力停止处理正在执行的任务之外, 没有任何保证.
     * 此实现通过{@link Thread#interrupt}取消任务, 因此任何未能响应中断的任务
     * 都可能永远不会终止.
     *
     * @throws SecurityException {@inheritDoc}
     */
    public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);
            interruptWorkers();
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

    public boolean isShutdown() {
        return ! isRunning(ctl.get());
    }

    /**
     * 如果此executor在{@link #shutdown}或{@link #shutdownNow}之后
     * 正在终止, 但尚未完全终止, 则返回true. 此方法可能对调试有用.
     * 如果{@code true}在关闭后足够长的时间内返回, 则可能表明提交的任务忽略
     * 或抑制了中断, 从而导致该executor无法正确终止.
     *
     * @return {@code true} 如果正在终止中但尚未终止
     */
    public boolean isTerminating() {
        int c = ctl.get();
        return ! isRunning(c) && runStateLessThan(c, TERMINATED);
    }

    public boolean isTerminated() {
        return runStateAtLeast(ctl.get(), TERMINATED);
    }

    public boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (;;) {
                if (runStateAtLeast(ctl.get(), TERMINATED))
                    return true;
                if (nanos <= 0)
                    return false;
                nanos = termination.awaitNanos(nanos);
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 当executor不再被引用并且没有线程时调用{@code shutdown}.
     */
    protected void finalize() {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null || acc == null) {
            shutdown();
        } else {
            PrivilegedAction<Void> pa = () -> { shutdown(); return null; };
            AccessController.doPrivileged(pa, acc);
        }
    }

    /**
     * 设置用于创建新线程的线程工厂.
     *
     * @param threadFactory 新线程的工厂
     * @throws NullPointerException 如果threadFactory为null
     * @see #getThreadFactory
     */
    public void setThreadFactory(ThreadFactory threadFactory) {
        if (threadFactory == null)
            throw new NullPointerException();
        this.threadFactory = threadFactory;
    }

    /**
     * 返回用于创建新线程的线程工厂.
     *
     * @return 当前线程工厂
     * @see #setThreadFactory(ThreadFactory)
     */
    public ThreadFactory getThreadFactory() {
        return threadFactory;
    }

    /**
     * 为不可执行的任务设置新的handler.
     *
     * @param handler the new handler
     * @throws NullPointerException 如果handler为null
     * @see #getRejectedExecutionHandler
     */
    public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
        if (handler == null)
            throw new NullPointerException();
        this.handler = handler;
    }

    /**
     * 返回不可执行任务的当前handler.
     *
     * @return the current handler
     * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
     */
    public RejectedExecutionHandler getRejectedExecutionHandler() {
        return handler;
    }

    /**
     * 设置核心线程数. 这将覆盖构造函数中设置的任何值. 如果新值小于当前值,
     * 则多余的现有线程将在下次空闲时终止. 如果更大, 如果需要, 将启动新线程来执行
     * 任何排队的任务.
     *
     * @param corePoolSize the new core size
     * @throws IllegalArgumentException 如果{@code corePoolSize < 0}
     * @see #getCorePoolSize
     */
    public void setCorePoolSize(int corePoolSize) {
        if (corePoolSize < 0)
            throw new IllegalArgumentException();
        int delta = corePoolSize - this.corePoolSize;
        this.corePoolSize = corePoolSize;
        if (workerCountOf(ctl.get()) > corePoolSize)
            interruptIdleWorkers();
        else if (delta > 0) {
            // 我们诊断不知道"需要"多少新线程.
            // 作为一种启发式方法, 预先启动足够多的新worker(达到新的core大小)
            // 来处理队列中的当前任务数量, 但如果在执行此操作时队列变空, 则停止.
            int k = Math.min(delta, workQueue.size());
            while (k-- > 0 && addWorker(null, true)) {
                if (workQueue.isEmpty())
                    break;
            }
        }
    }

    /**
     * 返回线程的core数.
     *
     * @return 线程的core数
     * @see #setCorePoolSize
     */
    public int getCorePoolSize() {
        return corePoolSize;
    }

    /**
     * 启动一个core线程, 使其空闲等待工作. 这将覆盖只有在执行新任务时才启动核心线程
     * 的默认策略. 如果所有核心线程都已启动, 则此方法将返回{@code false}.
     *
     * @return {@code true} 如果启动了线程
     */
    public boolean prestartCoreThread() {
        return workerCountOf(ctl.get()) < corePoolSize &&
            addWorker(null, true);
    }

    /**
     * 与prestartCoreThread相同, 不同之处在于即使corePoolSize为0,
     * 也会安排至少启动一个线程.
     */
    void ensurePrestart() {
        int wc = workerCountOf(ctl.get());
        if (wc < corePoolSize)
            addWorker(null, true);
        else if (wc == 0)
            addWorker(null, false);
    }

    /**
     * 启动所有核心线程, 使它们空闲等待工作.
     * 这将覆盖只有在执行新任务时才启动核心线程的默认策略.
     *
     * @return 启动的线程数
     */
    public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true))
            ++n;
        return n;
    }

    /**
     * 如果此poll允许核心线程超时, 并且在keepAlive时间内没有任务到达时终止,
     * 则返回true, 如果需要, 则在新任务达到时替换. 如果为true, 则应用于非核心
     * 线程的保持活动策略也使用与核心线程. 当为false(默认值)时, 核心线程永远不会
     * 因为缺少传入任务而终止.
     *
     * @return {@code true} 如果允许核心线程超时, 否则为{@code false}
     *
     * @since 1.6
     */
    public boolean allowsCoreThreadTimeOut() {
        return allowCoreThreadTimeOut;
    }

    /**
     * Sets the policy governing whether core threads may time out and
     * terminate if no tasks arrive within the keep-alive time, being
     * replaced if needed when new tasks arrive. When false, core
     * threads are never terminated due to lack of incoming
     * tasks. When true, the same keep-alive policy applying to
     * non-core threads applies also to core threads. To avoid
     * continual thread replacement, the keep-alive time must be
     * greater than zero when setting {@code true}. This method
     * should in general be called before the pool is actively used.
     *
     * @param value {@code true} if should time out, else {@code false}
     * @throws IllegalArgumentException if value is {@code true}
     *         and the current keep-alive time is not greater than zero
     *
     * @since 1.6
     */
    public void allowCoreThreadTimeOut(boolean value) {
        if (value && keepAliveTime <= 0)
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        if (value != allowCoreThreadTimeOut) {
            allowCoreThreadTimeOut = value;
            if (value)
                interruptIdleWorkers();
        }
    }

    /**
     * Sets the maximum allowed number of threads. This overrides any
     * value set in the constructor. If the new value is smaller than
     * the current value, excess existing threads will be
     * terminated when they next become idle.
     *
     * @param maximumPoolSize the new maximum
     * @throws IllegalArgumentException if the new maximum is
     *         less than or equal to zero, or
     *         less than the {@linkplain #getCorePoolSize core pool size}
     * @see #getMaximumPoolSize
     */
    public void setMaximumPoolSize(int maximumPoolSize) {
        if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
            throw new IllegalArgumentException();
        this.maximumPoolSize = maximumPoolSize;
        if (workerCountOf(ctl.get()) > maximumPoolSize)
            interruptIdleWorkers();
    }

    /**
     * Returns the maximum allowed number of threads.
     *
     * @return the maximum allowed number of threads
     * @see #setMaximumPoolSize
     */
    public int getMaximumPoolSize() {
        return maximumPoolSize;
    }

    /**
     * Sets the time limit for which threads may remain idle before
     * being terminated.  If there are more than the core number of
     * threads currently in the pool, after waiting this amount of
     * time without processing a task, excess threads will be
     * terminated.  This overrides any value set in the constructor.
     *
     * @param time the time to wait.  A time value of zero will cause
     *        excess threads to terminate immediately after executing tasks.
     * @param unit the time unit of the {@code time} argument
     * @throws IllegalArgumentException if {@code time} less than zero or
     *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
     * @see #getKeepAliveTime(TimeUnit)
     */
    public void setKeepAliveTime(long time, TimeUnit unit) {
        if (time < 0)
            throw new IllegalArgumentException();
        if (time == 0 && allowsCoreThreadTimeOut())
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        long keepAliveTime = unit.toNanos(time);
        long delta = keepAliveTime - this.keepAliveTime;
        this.keepAliveTime = keepAliveTime;
        if (delta < 0)
            interruptIdleWorkers();
    }

    /**
     * Returns the thread keep-alive time, which is the amount of time
     * that threads in excess of the core pool size may remain
     * idle before being terminated.
     *
     * @param unit the desired time unit of the result
     * @return the time limit
     * @see #setKeepAliveTime(long, TimeUnit)
     */
    public long getKeepAliveTime(TimeUnit unit) {
        return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
    }

    /* User-level queue utilities */

    /**
     * Returns the task queue used by this executor. Access to the
     * task queue is intended primarily for debugging and monitoring.
     * This queue may be in active use.  Retrieving the task queue
     * does not prevent queued tasks from executing.
     *
     * @return the task queue
     */
    public BlockingQueue<Runnable> getQueue() {
        return workQueue;
    }

    /**
     * Removes this task from the executor's internal queue if it is
     * present, thus causing it not to be run if it has not already
     * started.
     *
     * <p>This method may be useful as one part of a cancellation
     * scheme.  It may fail to remove tasks that have been converted
     * into other forms before being placed on the internal queue. For
     * example, a task entered using {@code submit} might be
     * converted into a form that maintains {@code Future} status.
     * However, in such cases, method {@link #purge} may be used to
     * remove those Futures that have been cancelled.
     *
     * @param task the task to remove
     * @return {@code true} if the task was removed
     */
    public boolean remove(Runnable task) {
        boolean removed = workQueue.remove(task);
        tryTerminate(); // In case SHUTDOWN and now empty
        return removed;
    }

    /**
     * Tries to remove from the work queue all {@link Future}
     * tasks that have been cancelled. This method can be useful as a
     * storage reclamation operation, that has no other impact on
     * functionality. Cancelled tasks are never executed, but may
     * accumulate in work queues until worker threads can actively
     * remove them. Invoking this method instead tries to remove them now.
     * However, this method may fail to remove tasks in
     * the presence of interference by other threads.
     */
    public void purge() {
        final BlockingQueue<Runnable> q = workQueue;
        try {
            Iterator<Runnable> it = q.iterator();
            while (it.hasNext()) {
                Runnable r = it.next();
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
                    it.remove();
            }
        } catch (ConcurrentModificationException fallThrough) {
            // Take slow path if we encounter interference during traversal.
            // Make copy for traversal and call remove for cancelled entries.
            // The slow path is more likely to be O(N*N).
            for (Object r : q.toArray())
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
                    q.remove(r);
        }

        tryTerminate(); // In case SHUTDOWN and now empty
    }

    /* Statistics */

    /**
     * Returns the current number of threads in the pool.
     *
     * @return the number of threads
     */
    public int getPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            // Remove rare and surprising possibility of
            // isTerminated() && getPoolSize() > 0
            return runStateAtLeast(ctl.get(), TIDYING) ? 0
                : workers.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate number of threads that are actively
     * executing tasks.
     *
     * @return the number of threads
     */
    public int getActiveCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            int n = 0;
            for (Worker w : workers)
                if (w.isLocked())
                    ++n;
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the largest number of threads that have ever
     * simultaneously been in the pool.
     *
     * @return the number of threads
     */
    public int getLargestPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            return largestPoolSize;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate total number of tasks that have ever been
     * scheduled for execution. Because the states of tasks and
     * threads may change dynamically during computation, the returned
     * value is only an approximation.
     *
     * @return the number of tasks
     */
    public long getTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers) {
                n += w.completedTasks;
                if (w.isLocked())
                    ++n;
            }
            return n + workQueue.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate total number of tasks that have
     * completed execution. Because the states of tasks and threads
     * may change dynamically during computation, the returned value
     * is only an approximation, but one that does not ever decrease
     * across successive calls.
     *
     * @return the number of tasks
     */
    public long getCompletedTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers)
                n += w.completedTasks;
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns a string identifying this pool, as well as its state,
     * including indications of run state and estimated worker and
     * task counts.
     *
     * @return a string identifying this pool, as well as its state
     */
    public String toString() {
        long ncompleted;
        int nworkers, nactive;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            ncompleted = completedTaskCount;
            nactive = 0;
            nworkers = workers.size();
            for (Worker w : workers) {
                ncompleted += w.completedTasks;
                if (w.isLocked())
                    ++nactive;
            }
        } finally {
            mainLock.unlock();
        }
        int c = ctl.get();
        String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
                     (runStateAtLeast(c, TERMINATED) ? "Terminated" :
                      "Shutting down"));
        return super.toString() +
            "[" + rs +
            ", pool size = " + nworkers +
            ", active threads = " + nactive +
            ", queued tasks = " + workQueue.size() +
            ", completed tasks = " + ncompleted +
            "]";
    }

    /* Extension hooks */

    /**
     * Method invoked prior to executing the given Runnable in the
     * given thread.  This method is invoked by thread {@code t} that
     * will execute task {@code r}, and may be used to re-initialize
     * ThreadLocals, or to perform logging.
     *
     * <p>This implementation does nothing, but may be customized in
     * subclasses. Note: To properly nest multiple overridings, subclasses
     * should generally invoke {@code super.beforeExecute} at the end of
     * this method.
     *
     * @param t the thread that will run task {@code r}
     * @param r the task that will be executed
     */
    protected void beforeExecute(Thread t, Runnable r) { }

    /**
     * Method invoked upon completion of execution of the given Runnable.
     * This method is invoked by the thread that executed the task. If
     * non-null, the Throwable is the uncaught {@code RuntimeException}
     * or {@code Error} that caused execution to terminate abruptly.
     *
     * <p>This implementation does nothing, but may be customized in
     * subclasses. Note: To properly nest multiple overridings, subclasses
     * should generally invoke {@code super.afterExecute} at the
     * beginning of this method.
     *
     * <p><b>Note:</b> When actions are enclosed in tasks (such as
     * {@link FutureTask}) either explicitly or via methods such as
     * {@code submit}, these task objects catch and maintain
     * computational exceptions, and so they do not cause abrupt
     * termination, and the internal exceptions are <em>not</em>
     * passed to this method. If you would like to trap both kinds of
     * failures in this method, you can further probe for such cases,
     * as in this sample subclass that prints either the direct cause
     * or the underlying exception if a task has been aborted:
     *
     *  <pre> {@code
     * class ExtendedExecutor extends ThreadPoolExecutor {
     *   // ...
     *   protected void afterExecute(Runnable r, Throwable t) {
     *     super.afterExecute(r, t);
     *     if (t == null && r instanceof Future<?>) {
     *       try {
     *         Object result = ((Future<?>) r).get();
     *       } catch (CancellationException ce) {
     *           t = ce;
     *       } catch (ExecutionException ee) {
     *           t = ee.getCause();
     *       } catch (InterruptedException ie) {
     *           Thread.currentThread().interrupt(); // ignore/reset
     *       }
     *     }
     *     if (t != null)
     *       System.out.println(t);
     *   }
     * }}</pre>
     *
     * @param r the runnable that has completed
     * @param t the exception that caused termination, or null if
     * execution completed normally
     */
    protected void afterExecute(Runnable r, Throwable t) { }

    /**
     * Method invoked when the Executor has terminated.  Default
     * implementation does nothing. Note: To properly nest multiple
     * overridings, subclasses should generally invoke
     * {@code super.terminated} within this method.
     */
    protected void terminated() { }

    /* Predefined RejectedExecutionHandlers */

    /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }
}
